package com.mediacloud.app.newsmodule.fragment.imagetext;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDLocation;
import com.eventTrack.TXReportManager;
import com.google.zxing.DecodeHintType;
import com.king.zxing.util.CodeUtils;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.FileFormatUtils;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.ILocation;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.CustomColumns;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.CancelUtils;
import com.mediacloud.app.model.utils.NeedTokenType;
import com.mediacloud.app.model.view.WebBrowser;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.HandleDataCollectActivity;
import com.mediacloud.app.newsmodule.activity.MagazineDetailActivity;
import com.mediacloud.app.newsmodule.activity.WebViewPageActivity;
import com.mediacloud.app.newsmodule.adaptor.adv.DetailAdvBaseHolder;
import com.mediacloud.app.newsmodule.adaptor.component.IExposure;
import com.mediacloud.app.newsmodule.broadcast.PowerStateReciver;
import com.mediacloud.app.newsmodule.fragment.military.MilitaryCalendarFragment;
import com.mediacloud.app.newsmodule.fragment.webview.WebViewFragment;
import com.mediacloud.app.newsmodule.javascript.H5PayJavaScriptInterface;
import com.mediacloud.app.newsmodule.model.AddHistoryParamsData;
import com.mediacloud.app.newsmodule.model.JSImgItem;
import com.mediacloud.app.newsmodule.pay.GiveMoneyDialog;
import com.mediacloud.app.newsmodule.pay.GivenMoneyPeopleListAdapter;
import com.mediacloud.app.newsmodule.pay.PaidMetas;
import com.mediacloud.app.newsmodule.utils.AdDataInvoker;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.AppfacBuyEnableUtils;
import com.mediacloud.app.newsmodule.utils.CollectionController;
import com.mediacloud.app.newsmodule.utils.HistoryInvoker;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.MJavaScriptInterface;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.ShareGridClickUtil;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.newsmodule.utils.WebViewInsertHandle;
import com.mediacloud.app.newsmodule.utils.WebViewLinkCMSNewsHandle;
import com.mediacloud.app.newsmodule.utils.spider.IAttentionCall;
import com.mediacloud.app.newsmodule.view.BaseSpiderView;
import com.mediacloud.app.newsmodule.view.ShareComponent;
import com.mediacloud.app.newsmodule.view.WeatherSetter;
import com.mediacloud.app.newsmodule.view.WebInsertAudioView;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.share.model.ShareGridItem;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.appcloud.project.gxapp.model.utils.TimeUtils;
import com.tencent.mmkv.MMKV;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlinx.coroutines.Job;
import retrofit2.Response;
import xyz.doikki.videoplayer.player.VideoView;


/**
 * Created by x on 2017/7/13.
 */
@SuppressWarnings("all")
public class MagazineDetailFragment extends Fragment implements DataInvokeCallBack<ArticleItemReciver>, WebBrowser.ZoomTouchListener, View.OnClickListener, GiveMoneyDialog.GivenMoneyStatus, IAttentionCall {

    /**
     * 是否来自点播  默认不是
     */
    public static final String FROM_VOD = "FROM_VOD";

    public static final String FROM_MICROLIVE = "FROM_MICROLIVE";

    public static final String FROM_SHANSHIPIN = "FROM_SHANSHIPIN";
    //阅读数接口是否已经请求成功
    protected boolean readResponsed = false;

    protected NestedScrollView mScrollView;
    //WebView
    public WebBrowser mWebView;
    //文稿标题
    protected TextView tvNewsTitle;
    protected TextView text_sub_tile;
    protected TextView magazine_author;
    //副标题
    protected TextView text_short_title;
    //支付的对话框
    private GiveMoneyDialog giveMoneyDialog;

    //文稿对象
    protected ArticleItem article;
    //头部信息的容器 包括普通文稿样式 样式 自媒体样式
    protected ViewGroup layoutRootTitleInfo;
    private ShowSwitch showSwitch;

    //作者
    protected TextView tvAuthor;
    protected TextView tvAuthorBottom;
    protected View layoutAuthorName;
    //来源
    protected TextView tvSource;
    protected TextView ePagerSource;
    protected TextView ePagerAuthor;
    //发布日期
    protected TextView tvPublishDate;

    //阅读数
    protected TextView tvReadNumber;
    //查看原文
    protected TextView tvOriginal;
    //转载
    protected TextView tvReprint;
    //原创标识
    protected ConstraintLayout normalInfoLayout;
    protected TextView originalLabel;
    protected View bottomLine;

    protected BaseSpiderView spiderView;

    //视频的ViewStub
    private View videoLayout;
    //播放器
    private XPlayer mVideoPlayer;
    //视频Poster
    //private ImageView ivVideoThumb;


    protected CatalogItem catalogItem;
    private VideoAdDataCallBack videoAdDataCallBack;
    private AdDataInvoker adDataInvoker;
    private boolean isVoteMode = false;
    private String orginHTMLData;
    //JS相关的
    public static final String Js2GroupImage = "Js2GroupImage";
    public static final String WebImgClick = "webImgClick";
    public static final String ANDROID_IFRAME = "android_iframe";
    public static final String XIN_ZHI_GET = "xin_zhi";
    public static final String APPFACTORY_CLIENT_LOCAL_FONT_SRC = "APPFACTORY_CLIENT_LOCAL_FONT_SRC";
    public static final String PACKAGE_FONT_SRC = "file:///android_asset/font/font.ttf";

    public static final String NATIVE_STORAGE_PREFIX = "file://";
    public static final String TAG = "111";
    public static final Map<String, String> iframe_vote_releationship = new HashMap<String, String>();
    /**
     * 静态变量来存放列表返回的详情页数据
     */
    public static final String summaryStr;
    public String magazineAuthor;
    //标记是否是使用的列表页数据

    protected WeatherSetter weatherSetter;
    boolean isLoaded = false;
    /**
     * 保存网页里面的全部图集
     */
    protected ArrayList<JSImgItem> webImages = new ArrayList<JSImgItem>();
    private FragmentManager manager;
    private FragmentTransaction transaction;

    public WebViewInsertHandle webViewInsertHandle;
    //播放器的容器层 ，单独存在的 用于可以悬浮到顶部
    private AbsoluteLayout floatPlayerContainer;
    //private FrameLayout webViewContainer;
    private PowerStateReciver powerStateReciver;


    private DetailAdvBaseHolder detailAdTopHolder, detailAdBottomHolder;


    //打赏控件
    protected View rewardView;
    protected GivenMoneyPeopleListAdapter givenMoneyPeopleListAdapter;
    protected RecyclerView giveMoneyPeople;
    protected TextView tvRewardTitle;

    boolean fromMicroLive = false;
    public boolean fromShanShiPin = false;
    private CollectionController collectionController;
    // private PayAmountListener amountListener;
    protected AppFactoryGlobalConfig.ServerAppConfigInfo serverInfo;
    protected ShowSwitch mShowSwitch;
    // 是否来自点播 这个标记为好像是没用的。先保留
    protected boolean isFromeVod;
    // private RelatedRecommendationListFragment rrf;
    private Job job;
    //防止多次加载 onPageFinished 后只加载一次其他View
    protected boolean isOtherAdded = false;
    //不为空的时候说明已经取到了数据，用于网页onPageFinished的后续流程
    protected ArticleItemReciver mArticleItemReciver;
    //获取详情后是否需要执行下面的流程  网页onPageFinished 后才会true
    protected boolean onDetailNext = false;

    public boolean isDispose() {
        return isDispose;
    }

    boolean isDispose = false;

    public void setMicroLiveWebBackGround() {
    }

    View mRootView;
    public long time;
    public static final  String NEED_TO_PAY = "1";
    View summaryLayout;
    TextView summaryTv;
    protected int playNormalWidth;
    protected int playNormalHeight;
    private File renamedFile;

    private HistoryInvoker HistoryInvoker;
    public boolean isCalendar;

    public ArrayList<Thread> threadList = new ArrayList<>();

    private CancelUtils cancelUtils;

    LinearLayout container = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        time = System.currentTimeMillis();
        mRootView = inflater.inflate(getLayoutResID(), container, false);
        isDispose = false;
        initArgs();
        initView();
        return mRootView;
    }

    public void stopInsertVideoAudio() {
        if (webViewInsertHandle.videoPlayer != null && webViewInsertHandle.videoPlayer.isPlaying()) {
            webViewInsertHandle.videoPlayer.pause();
        }
        for (View view : webViewInsertHandle.nativeControls) {
            if (view instanceof WebInsertAudioView) {
                ((WebInsertAudioView) view).reset();
            }
        }
    }

    protected void initArgs() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        Bundle bundle = getArguments();
        isCalendar = bundle.getBoolean("IS_CALENDAR");
        catalogItem = bundle.getParcelable("catalog");
        article = bundle.getParcelable("data");
        if (article != null) {
            showSwitch = article.mShowSwitch;
            magazineAuthor = article.Author;
        }

        isFromeVod = bundle.getBoolean(FROM_VOD, false);
        fromMicroLive = bundle.getBoolean(FROM_MICROLIVE, false);
        fromShanShiPin = bundle.getBoolean(FROM_SHANSHIPIN, false);
    }

    public int getLayoutResID() {
        return R.layout.fragment_magazine_detail_layout;
    }

    public void initView() {
        findViewById();
        initInstance();
        initOther();
        registerReceiver();
        setScrollListener();
        addJavaScript();
        setMicroLiveWebBackGround();
        //setQuickData();
        //getNewsDetail();
        getDetail();
        setContentData();
        HistoryInvoker = new HistoryInvoker();
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                int type = result.getType();
                if (WebView.HitTestResult.IMAGE_TYPE == type) {
                    String imgurl = result.getExtra();
                    PermissionUtil.INSTANCE.invokeStoragePermission(getActivity(), new IPermissionsAgree() {
                        @Override
                        public void onAgree() {
                            new SaveImage().execute(imgurl);
                        }

                        @Override
                        public void onRefuse() {
                        }

                        @Override
                        public void hasPermissions() {
                            new SaveImage().execute(imgurl);
                        }
                    });
                }
                return false;
            }
        });
        // showActivityStateView(TYPE_LOADING);
        initMPScanner();
        AddMedalStatistics.addMedalStatistics(requireContext()); //勋章统计
        if (!isCalendar) {
            addintegral();
        }
    }

    private void addHistory() {
        AddHistoryParamsData paramsData = new AddHistoryParamsData();
        paramsData.source = CollectionController.convertToSource(catalogItem);
        if (article.getId() > 0) {
            paramsData.source_id = article.getId();
        } else {
            if (!TextUtils.isEmpty(article.getReferTarget())) {
                try {
                    paramsData.source_id = Long.parseLong(article.getReferTarget());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        paramsData.summary = article.getSummary();
        paramsData.title = article.getTitle();
        paramsData.type = article.getType() + "";
        paramsData.url = article.getUrl();
        paramsData.logo = article.getLogo();
        paramsData.publishdate_format = article.getPublishdate_format();
        paramsData.isFromEpaper = article.isEPaper ? "1" : "0";
        paramsData.logoImgSize = article.getLogoImgSize();
        HistoryInvoker.addHistory(UserInfo.getUserInfo(getContext()).getUserid(), paramsData, null);
    }

    private void initMPScanner() {
//        mpScanner = new MPScanner(getContext());
//        mpScanner.setRecognizeType(
//                MPRecognizeType.QR_CODE,
//                MPRecognizeType.BAR_CODE,
//                MPRecognizeType.DM_CODE,
//                MPRecognizeType.PDF417_CODE
//        );

    }

    private void scanFromUri(String path) {
        if (!TextUtils.isEmpty(path)) {
//				String path=list.get(0);
            Log.w(TAG, "location choose pic path:" + path);
//            LocalImageDecodeZBar decode = new LocalImageDecodeZBar(new LocalImageDecodeZBar.LocalDecodeResult() {
//
//                @Override
//                public void localImageResult(String result) {
//                    Intent resultIntent = new Intent();
//                    resultIntent.putExtra(Intent.ACTION_ATTACH_DATA, result);
//                    if (TextUtils.isEmpty(result)) {
//                        ToastUtil.show(getContext(), R.string.not_found_crcode);
//                    } else {
//                        if (URLUtil.isNetworkUrl(result.toLowerCase()))//如果抛投的二维码是网址
//                        {
//                            getServerMathChar(result);
//                        } else {
//                            ToastUtil.showCustomView(getContext(), getResources().getString(R.string.qrcode_scanresult) + result);
//                        }
//                    }
//                }
//            });
//            decode.executeOnExecutor(Executors.newCachedThreadPool(), path);


            try {
                Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true; // 先获取原大小
                Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);
                options.inJustDecodeBounds = false; // 获取新的大小
                int sampleSize = (int) (options.outHeight / (float) 200);
                if (sampleSize <= 0)
                    sampleSize = 1;
                options.inSampleSize = sampleSize;
                scanBitmap = BitmapFactory.decodeFile(path, options);
                File file = new File(path);
                //异步解析
                Bitmap finalScanBitmap = scanBitmap;
                asyncThread(() -> {
                    final String result = CodeUtils.parseCode(finalScanBitmap);
                    getActivity().runOnUiThread(() -> {
                        Intent resultIntent = new Intent();
                        resultIntent.putExtra(Intent.ACTION_ATTACH_DATA, result);
                        if (!TextUtils.isEmpty(result)) {
                            if (URLUtil.isNetworkUrl(result.toLowerCase()))//如果抛投的二维码是网址
                            {
                                getServerMathChar(result);
                            } else {
                                ToastUtil.showCustomView(getContext(), getResources().getString(R.string.qrcode_scanresult) + result);
                            }
                        }
                    });
                    file.delete();
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void asyncThread(Runnable runnable) {
        Thread thread = new Thread(runnable);
        threadList.add(thread);
        thread.start();
    }

    public void getServerMathChar(String decodeChar) {
        if (WebViewLinkCMSNewsHandle.handleCMSNews(decodeChar, getContext(), new ArticleItem(), new CatalogItem())) {

            return;
        }
        int needToken = NeedTokenType.Delayed;
        ArticleItem articleItem = new ArticleItem();
//        articleItem.setTitle(this.getResources().getString(R.string.wangye));
        articleItem.setLinkNews(false);
        articleItem.setUrl(decodeChar);
        articleItem.setType(TypeX.NEWS.LINK);
        articleItem.setIsComment("0");
        articleItem.setLinkNews(false);
        NewsItemClickUtils.OpenItemNewsHandle(getContext(), TypeX.NEWS.LINK, articleItem, new CatalogItem(), needToken, false);
    }

   /* private void onScanSuccess(final MPScanResult result) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result == null) {
                    onScanResult(null);
                } else {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse(result.getText()));
                    onScanResult(intent);
                }

            }
        });
    }*/

    public void onScanResult(Intent result) {
        if (result == null || result.getData() == null) {
            ToastUtil.show(getContext(), "识别失败");
            return;
        }
        WebViewPageActivity.start("", result.getData().toString(), getActivity());
        if (renamedFile.exists()) {
           if(!renamedFile.delete()) {
                ToastUtil.show(getContext(), "删除失败");
           }
        }
    }

    public void setUpdateTheData(ArticleItem articleItem) {
        //  tvPublishDate.setText(articleItem.getPublishdate_format());
        try {
            tvPublishDate.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(TimeUtils.toDate(articleItem.getPublishdate())));
        } catch (Exception e) {
            tvPublishDate.setText(articleItem.getPublishdate());
        }

        article = articleItem;
        handler.sendEmptyMessageDelayed(0, 1000);
        MagazineDetailKitKt.updateSpiderViewUI(this);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            addHistory();
        }
    };

    /***
     * 功能：用线程保存图片
     *
     * @author wangyp
     */
    private class SaveImage extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... params) {
            if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                return "";
            }
            String result = "";
            InputStream inputStream = null;
            FileOutputStream outStream = null;
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                final String SUFFIX = ".imgtype";
                file = new File(sdcard + "/Download/" + getResources().getString(R.string.tenantid) + "_" + new Date().getTime() + SUFFIX);
                    // 关键：解析真实路径，防止符号链接绕过
                   // 关键：解析真实路径，防止符号链接绕过
                String canonicalPath = file.getCanonicalPath();
                String allowedDir = new File(sdcard, "Download").getCanonicalPath();

                if (!canonicalPath.startsWith(allowedDir)) {
                    throw new SecurityException("非法路径: " + canonicalPath);
                }
                URL url = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                conn.setDoInput(true);
                conn.connect();
                Log.e("", "==dow== " + conn.getResponseCode());
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    byte[] buffer = new byte[4096];
                    int len = 0;
                    outStream = new FileOutputStream(file);
                    while ((len = inputStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();
                    String path = file.getAbsolutePath();
                    FileFormatUtils.FileType fileType = FileFormatUtils.getType(path);
                    if (fileType == FileFormatUtils.FileType.GIF) {
                        path = path.replace(SUFFIX, ".gif");
                    } else if (fileType == FileFormatUtils.FileType.JPEG) {
                        path = path.replace(SUFFIX, ".jpg");
                    } else if (fileType == FileFormatUtils.FileType.PNG) {
                        path = path.replace(SUFFIX, ".png");
                    } else if (fileType == FileFormatUtils.FileType.BMP) {
                        path = path.replace(SUFFIX, ".bmp");
                    }
                    renamedFile = new File(path);
                    file.renameTo(renamedFile);
                    result = getResources().getString(R.string.image_besaved);
                    Utility.insertIntoMediaStore(getContext(), false, renamedFile, renamedFile.lastModified());
                } else {
                    result = getResources().getString(R.string.image_save_failed);
                }
            } catch (Exception e) {

                result = getResources().getString(R.string.image_save_failed);
            } finally {
                try {
                    if (outStream != null) {
                        outStream.flush();
                        outStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            return renamedFile.getAbsolutePath();
        }

        @Override
        protected void onPostExecute(String result) {
            if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                return;
            }
//            FunKt.toastCenter(getContext(), result, false);
            scanFromUri(result);
        }

    }


    protected void initOther() {

        if (needPaidReading() && getActivity() instanceof MagazineDetailActivity) {
            AppfacBuyEnableUtils.refresh(getActivity(), false);
        }
        int fontSize = MMKV.defaultMMKV().getInt(XKey.NEWS_FONT_SIZE, 1);
        resizeFont(fontSize, AppConfig.zoomSize.get(fontSize));
    }

    /**
     * 实例化一些对象
     */
    private void initInstance() {
        if (catalogItem == null) catalogItem = new CatalogItem();
        if (article == null) article = new ArticleItem();

        mShowSwitch = article.getmShowSwitch();
        serverInfo = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity());
        powerStateReciver = new PowerStateReciver();

        collectionController = new CollectionController(getActivity(), catalogItem, article, null);
        webViewInsertHandle = new WebViewInsertHandle(getActivity(), article, catalogItem, mWebView);
        webViewInsertHandle.floatPlayerContainer = floatPlayerContainer;
        //webViewInsertHandle.webViewContainer =webViewContainer;
        mWebView.zoomTouchListener = this;
    }


    /**
     * 初始化控件 findViewById 统一放到这里处理
     */
    private void findViewById() {
        //   webViewContainer =mRootView.findViewById(R.id.webViewContainer);
        summaryLayout = mRootView.findViewById(R.id.summaryLayout);
        summaryTv = mRootView.findViewById(R.id.summaryTv);
        floatPlayerContainer = mRootView.findViewById(R.id.floatPlayerContainer);
        mScrollView = mRootView.findViewById(R.id.mNewsdetailContent);
        mWebView = mRootView.findViewById(R.id.mNewsContentView);
        tvAuthor = mRootView.findViewById(R.id.authorName);
        tvAuthorBottom = mRootView.findViewById(R.id.authorNameBottom);
        layoutAuthorName = mRootView.findViewById(R.id.layout_author_name);
        videoLayout = mRootView.findViewById(R.id.videoLayout);
        layoutRootTitleInfo = mRootView.findViewById(R.id.mNewsTitleContainer);
        tvNewsTitle = mRootView.findViewById(R.id.mNewsTitle);
        text_short_title = mRootView.findViewById(R.id.text_short_title);
        text_sub_tile = mRootView.findViewById(R.id.text_sub_tile);
        magazine_author = mRootView.findViewById(R.id.magazine_author);
        tvSource = mRootView.findViewById(R.id.mNewsSource);
        ePagerSource = mRootView.findViewById(R.id.ePagerSource);
        ePagerAuthor = mRootView.findViewById(R.id.ePagerAuthor);
        tvPublishDate = mRootView.findViewById(R.id.mNewsPublishDate);
        tvReadNumber = mRootView.findViewById(R.id.newsHitCountLabel);
        tvOriginal = mRootView.findViewById(R.id.tvOriginal);
        tvReprint = mRootView.findViewById(R.id.tvReprint);
        normalInfoLayout = mRootView.findViewById(R.id.normalInfoLayout);
        originalLabel = mRootView.findViewById(R.id.originalLabel);
        bottomLine = mRootView.findViewById(R.id.view_line);
    }

    public void initReadNews() {

        if (serverInfo.show_text_audio == 1 && !TextUtils.isEmpty(article.getText_audio_url())) {

            MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
            if (activity != null) {
                activity.initReadView(article.getText_audio_url());
                //  activity.initReadView("http://ossweb-img2.qq.com/images/r2/a20070622zn/likai.mp3");
            }
        }
    }


    /**
     * 注册广播 电源线插入或取了的广播
     */
    private void registerReceiver() {
        IntentFilter powerFilter = new IntentFilter();
        powerFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        powerFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        getActivity().registerReceiver(powerStateReciver, powerFilter);
    }

    /**
     * 是否需要付费阅读
     *
     * @return
     */
    public boolean needPaidReading() {
        return NEED_TO_PAY.equals(article.getPayType());
    }


    /**
     * 设置快捷数据 列表页的数据
     */
    private void setQuickData() {

        //<!--产品 张强 确认 不要这里的简介 BUG ID 13657 -->
        if (false/*"zgjh".equals(AppFactoryGlobalConfig.getAppServerConfigInfo(requireContext()).code_method)*/) {
            if (!TextUtils.isEmpty(summaryStr)) {
                summaryLayout.setVisibility(View.VISIBLE);
                summaryTv.setText(getString(R.string.space2) + summaryStr);
            } else {
                summaryLayout.setVisibility(View.GONE);
            }
        } else {
            summaryLayout.setVisibility(View.GONE);
        }
        setNewsInfo();
        setMediaContent();
        MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
        summaryStr = null;
    }

    public void changeAttentionStatus() {
        if (UserInfo.isLogin(getContext())) {
            if (spiderView != null) {
                spiderView.attention();
            }
        } else {
            LoginUtils.request_source=LoginUtils.source_follow;
            LoginUtils.invokeLogin(getContext());
        }
    }

    /**
     * 设置ScrollView的一些监听
     */
    private void setScrollListener() {

        mScrollView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isFullScreen)
                    return false;
                EventBus.getDefault().post(event);
                return false;
            }
        });

        mScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            runTask();

            MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
            if (activity != null) {
                int offsetBottom = 0;
                if (spiderView != null) {
                    offsetBottom = spiderView.getBottom() + tvNewsTitle.getBottom();
                } else {
                    offsetBottom = tvNewsTitle.getBottom();
                }
                if (scrollY > offsetBottom) {
                    activity.onShowTitle(true);
                } else {
                    activity.onShowTitle(false);
                }
            }
            int contentHeight = mScrollView.getChildAt(0).getMeasuredHeight();
            float scrollPercent = (scrollY + mScrollView.getMeasuredHeight()) * 1F / contentHeight;
            if (getActivity() instanceof HandleDataCollectActivity) {
                ((HandleDataCollectActivity) getActivity()).setScrollProp(scrollPercent);
            }
            webViewInsertHandle.scrollY = scrollY;
            if (webViewInsertHandle.videoPlayer != null) {
                if (playNormalWidth == 0 && webViewInsertHandle.videoPlayer != null) {
                    playNormalWidth = webViewInsertHandle.videoPlayer.getMeasuredWidth();
                    playNormalHeight = webViewInsertHandle.videoPlayer.getMeasuredHeight();
                }
                Log.e("APPTAG-black_image", "setOnScrollChangeListener-scrollY: " + scrollY + ",playNormalWidth:" + playNormalWidth + ",playNormalHeight:" + playNormalHeight);
                if (scrollY >= webViewInsertHandle.playerTop + webViewInsertHandle.playerHeight) {
                    if (webViewInsertHandle.iv_video_black_bg != null) {
                        if (webViewInsertHandle.iv_video_black_bg.getVisibility() == View.VISIBLE) {
                            webViewInsertHandle.iv_video_black_bg.setVisibility(View.GONE);
                        }
                    }
                } else {
                    if (webViewInsertHandle.iv_video_black_bg != null) {
                        if (webViewInsertHandle.iv_video_black_bg.getVisibility() == View.GONE) {
                            webViewInsertHandle.iv_video_black_bg.setVisibility(View.VISIBLE);
                        }
                    }
                }
                if (webViewInsertHandle.needFloatPlay && scrollY > webViewInsertHandle.playerTop) {
                    int startY = webViewInsertHandle.playerTop;
                    floatPlayerContainer.scrollTo(0, startY);
                    int offset = scrollY - startY;

                    if (webViewInsertHandle.iv_video_black_bg != null) {
                        ViewGroup.LayoutParams black_lp = webViewInsertHandle.iv_video_black_bg.getLayoutParams();
                        if ((playNormalHeight - offset) <= 0) {
                            black_lp.height = 0;
                        } else {
                            black_lp.height = playNormalHeight - offset;
                        }
                        webViewInsertHandle.iv_video_black_bg.setLayoutParams(black_lp);
                        Log.e("APPTAG-black_image", "setOnScrollChangeListener-scrollY:true " + scrollY + ",offset:" + offset + ",playNormalWidth:" + playNormalWidth + ",playNormalHeight:" + black_lp.height);
                    }
                    if (offset < playNormalHeight * 1f / 2) {
//                        ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//                        lp.height = (int) (playNormalHeight - offset);
//                        lp.width = (int) (lp.height * 16f / 9);
//                        if(lp.height < playNormalHeight){
//                            webViewInsertHandle.iWindCloseComponent.setShow(true);
//                        }else{
//                            webViewInsertHandle.iWindCloseComponent.setShow(false);
//                        }
//                        webViewInsertHandle.videoPlayer.setLayoutParams(lp);

                        float scale = (playNormalHeight - offset) * 1f / playNormalHeight;
                        if (scale < 1f) {
                            webViewInsertHandle.iWindCloseComponent.setShow(true);
                        } else {
                            webViewInsertHandle.iWindCloseComponent.setShow(false);
                        }
                        webViewInsertHandle.videoPlayer.setPivotX(0);
                        webViewInsertHandle.videoPlayer.setPivotY(1);
                        webViewInsertHandle.videoPlayer.setScaleX(scale);
                        webViewInsertHandle.videoPlayer.setScaleY(scale);

//                        if (webViewInsertHandle.iv_video_black_bg!=null) {
//                            ViewGroup.LayoutParams black_lp = webViewInsertHandle.iv_video_black_bg.getLayoutParams();
//                            black_lp.height = lp.height;
//                            webViewInsertHandle.iv_video_black_bg.setLayoutParams(black_lp);
//                            Log.e("APPTAG-black_image","setOnScrollChangeListener-scrollY:true "+(offset < playNormalHeight * 1f / 2)+scrollY+",offset:"+offset+",playNormalWidth:"+playNormalWidth+",(playNormalHeight - offset):"+ lp.height);
//                        }
                    } else {

                        int maxWinHeight = (int) (playNormalHeight * 1f / 2);
//                        ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//                        if (lp.height != maxWinHeight) {
//                            lp.height = maxWinHeight;
//                            lp.width = (int) (lp.height * 16f / 9);
//                            if(lp.height < playNormalHeight){
//                                webViewInsertHandle.iWindCloseComponent.setShow(true);
//                            }else{
//                                webViewInsertHandle.iWindCloseComponent.setShow(false);
//                            }
//                            webViewInsertHandle.videoPlayer.setLayoutParams(lp);
//                        }

                        float minScale = maxWinHeight * 1f / playNormalHeight;

                        if (minScale != webViewInsertHandle.videoPlayer.getScaleX()) {
                            if (minScale < 1f) {
                                webViewInsertHandle.iWindCloseComponent.setShow(true);
                            } else {
                                webViewInsertHandle.iWindCloseComponent.setShow(false);
                            }
                            webViewInsertHandle.videoPlayer.setPivotX(0);
                            webViewInsertHandle.videoPlayer.setPivotY(1);
                            webViewInsertHandle.videoPlayer.setScaleX(minScale);
                            webViewInsertHandle.videoPlayer.setScaleY(minScale);
                        }

//                        if (webViewInsertHandle.iv_video_black_bg!=null) {
//                            ViewGroup.LayoutParams black_lp = webViewInsertHandle.iv_video_black_bg.getLayoutParams();
//                            black_lp.height = lp.height;
//                            webViewInsertHandle.iv_video_black_bg.setLayoutParams(black_lp);
//                            Log.e("APPTAG-black_image","setOnScrollChangeListener-scrollY:false "+scrollY+",offset:"+offset+",playNormalWidth:"+playNormalWidth+",maxWinHeight:"+ lp.height);
//                        }

                    }

                } else {
                    floatPlayerContainer.scrollTo(0, scrollY);
                    ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//                    if (lp.height != playNormalHeight) {
//                        lp.width = playNormalWidth;
//                        lp.height = playNormalHeight;
//                        if(lp.height < playNormalHeight){
//                            webViewInsertHandle.iWindCloseComponent.setShow(true);
//                        }else{
//                            webViewInsertHandle.iWindCloseComponent.setShow(false);
//                        }
//                        webViewInsertHandle.videoPlayer.setLayoutParams(lp);
//                    }

                    if (webViewInsertHandle.videoPlayer.getScaleX() != 1f) {
                        webViewInsertHandle.iWindCloseComponent.setShow(false);
                        webViewInsertHandle.videoPlayer.setPivotX(0);
                        webViewInsertHandle.videoPlayer.setPivotY(1);
                        webViewInsertHandle.videoPlayer.setScaleX(1f);
                        webViewInsertHandle.videoPlayer.setScaleY(1f);
                    }

                    if (webViewInsertHandle.iv_video_black_bg != null) {
                        ViewGroup.LayoutParams black_lp = webViewInsertHandle.iv_video_black_bg.getLayoutParams();
                        black_lp.height = lp.height;
                        webViewInsertHandle.iv_video_black_bg.setLayoutParams(black_lp);
                        Log.e("APPTAG-black_image", "setOnScrollChangeListener-scrollY:" + scrollY + ",playNormalWidth:" + playNormalWidth + ",playNormalHeight:" + lp.height);
                    }

                    //张强 说 继续播放，逻辑参照央视新闻 BUG ID 15935
//                    if ((scrollY + 2127) < webViewInsertHandle.playerTop) {
//                        if (webViewInsertHandle.videoViewPlaying()) {
//                            webViewInsertHandle.videoPlayer.pause();
//                            // webViewInsertHandle.videoPlayer.controlBarViewControl.setVisibility(View.VISIBLE);
//                        }
//                    }
                }
            }


//            if (scrollY > webViewInsertHandle.playerTop) {
//                if (webViewInsertHandle.playerTop > 0) {
//                    if (webViewInsertHandle.videoViewPlaying()) {
//                        floatPlayerContainer.scrollTo(0, webViewInsertHandle.playerTop);
//
//                        ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//                        int minWitdh = (int) (playNormalWidth -maxScaleWidth);
//                        if(lp.width!=minWitdh){
//                            lp.width= minWitdh;
//                            lp.height = (int) (lp.width*9f/16);
//                            webViewInsertHandle.videoPlayer.setLayoutParams(lp);
//                        }
//                        Log.w("XXAA0",""+scrollY);
//                    } else {
//                        floatPlayerContainer.scrollTo(0, scrollY);
//                        Log.w("XXAA1",""+scrollY);
//                    }
//                } else {
//                    floatPlayerContainer.scrollTo(0, scrollY);
//                    Log.w("XXAA2",""+scrollY);
//                }
//            } else {
//                if(webViewInsertHandle.videoPlayer.isPlaying()) {
//                    if (playNormalWidth == 0 && webViewInsertHandle.videoPlayer != null) {
//                        playNormalWidth =  webViewInsertHandle.videoPlayer.getMeasuredWidth();
//                        playNormalHeight = webViewInsertHandle.videoPlayer.getMeasuredHeight();
//                    }
//                    floatPlayerContainer.scrollTo(0, scrollY);
//                    int startY = webViewInsertHandle.playerTop;
//                    if (scrollY > startY) {
//                        float rate = (scrollY - startY) * 1f / playNormalHeight;
//                        ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//
//                        lp.width = (int) (playNormalWidth - (maxScaleWidth * rate));
//                        lp.height = (int) (lp.width * 9f / 16);
//                        webViewInsertHandle.videoPlayer.setLayoutParams(lp);
//                    } else {
//                        ViewGroup.LayoutParams lp = webViewInsertHandle.videoPlayer.getLayoutParams();
//                        if (lp.width != playNormalWidth) {
//                            lp.width = playNormalWidth;
//                            lp.height = (int) (lp.width * 9f / 16);
//                            webViewInsertHandle.videoPlayer.setLayoutParams(lp);
//                        }
//                    }
//                }
//                Log.w("XXAA3",""+scrollY);
//                //滑动到下方视频不见了以后就暂停播放
//                if ((scrollY + 2127) < webViewInsertHandle.playerTop) {
//                    if (webViewInsertHandle.videoViewPlaying()) {
//                        webViewInsertHandle.videoPlayer.pause();
//                       // webViewInsertHandle.videoPlayer.controlBarViewControl.setVisibility(View.VISIBLE);
//                    }
//                }
//            }
        });
    }

    /**
     * 注入JS
     */
    private void addJavaScript() {
        MJavaScriptInterface mInterface = new MJavaScriptInterface(getActivity(), mWebView);
        mWebView.addJavascriptInterface(mInterface, WebViewFragment.GETMFSIGN);
        mWebView.addJavascriptInterface(mInterface, WebViewFragment.ANDROID);
        H5PayJavaScriptInterface h5pay = new H5PayJavaScriptInterface(getActivity());
        mWebView.addJavascriptInterface(h5pay, WebViewFragment.H5PAY);

        mWebView.addJavascriptInterface(this, Js2GroupImage);
        mWebView.addJavascriptInterface(this, ANDROID_IFRAME);
        mWebView.addJavascriptInterface(this, XIN_ZHI_GET);
    }


//    public void setAmountListener(PayAmountListener amountListener) {
//        this.amountListener = amountListener;
//    }

    /**
     * 播放器是否为全屏
     */
    public boolean isFullScreen() {
        return mVideoPlayer != null && mVideoPlayer.isFullScreen();
    }

    public boolean onBackPressed() {
        boolean value = false;
        if (mVideoPlayer != null && mVideoPlayer.isFullScreen()) {
            //  mVideoPlayer.toggleFullScreen();
            mVideoPlayer.onBackPressed();
            value = true;
        }

        if (webViewInsertHandle != null && webViewInsertHandle.isFullScreen()) {
            value = true;
            webViewInsertHandle.toggleFullScreen();
        }
        return value;
    }

    protected void getVideoAd4(int type) {
        Log.e("ACVCC", "getVideoAd4 " + type + "  " + serverInfo.getAd_host());
        videoAdDataCallBack.type = type;
        adDataInvoker.getVideoAd("" + article.getCatalogId(), serverInfo.getAd_host(), getResources().getString(R.string.tenantid), type);
    }


    @Override
    public void zoomLarge() {
        final int index = MMKV.defaultMMKV().getInt(XKey.NEWS_FONT_SIZE, 1);
        if (index < AppConfig.zoomSize.size() - 1) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    resizeFont(index + 1, AppConfig.zoomSize.get(index + 1));
                }
            });
            webViewInsertHandle.resizeNativeControl();
        }
    }


    @Override
    public void zoomSmall() {
        final int index = MMKV.defaultMMKV().getInt(XKey.NEWS_FONT_SIZE, 1);
        if (index > 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    resizeFont(index - 1, AppConfig.zoomSize.get(index - 1));
                }
            });
            webViewInsertHandle.resizeNativeControl();
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.giveMoney) {
            if (giveMoneyDialog == null) {
                giveMoneyDialog = new GiveMoneyDialog(getActivity(), article);
                giveMoneyDialog.setGivenMoneyStatus(this);
            }
            giveMoneyDialog.show();
        }
    }

    @Override
    public void givenMoneyStatus(boolean state) {
        if (isDetached() || isDispose() || isRemoving())
            return;
        MagazineDetailKitKt.refreshGivenMoneyHead(this);
        if (state) {
            ToastUtil.showCustomView(getActivity(), "打赏成功");
        } else {
            ToastUtil.showCustomView(getActivity(), "打赏失败");
        }
    }

    public void resizeFont(int levelIndex, int zoom) {

        MMKV.defaultMMKV().putInt(XKey.NEWS_FONT_SIZE, levelIndex);
        Log.e(TAG, "resizeFont: " + levelIndex);
        float textSize = getActivity().getResources().getDimension(R.dimen.textsize_news_title) * (zoom / 100F);
        tvNewsTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        float textSize2 = getActivity().getResources().getDimension(R.dimen.dimen15) * (zoom / 100F);
        text_short_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize2);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setTextZoom(zoom);
        webViewInsertHandle.resizeNativeControl();
    }


    @Override
    public void onAttentionResult(boolean attention) {
        MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
        if (activity != null) {
            activity.spiderFollow.setSelected(attention);
            if (attention) {
                activity.spiderFollow.setText("+ 已关注");
            } else {
                activity.spiderFollow.setText("关注");
            }
        }

    }

    @Override
    public void onAttentionFail() {

    }

    class VideoAdDataCallBack implements DataInvokeCallBack<AdDataInvoker.AdDataReciver> {
        /**
         * 广告类型
         */
        public int type;

        @Override
        public void success(AdDataInvoker.AdDataReciver data) {
            if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                return;
            }
            Log.w(TAG, "ad success");
//            switch (type) {
//                case AdDataInvoker.BufferAd://片头广告请求完再请求片尾广告
//                    if (data.adList != null && data.adList.size() > 0) {
//                        mVideoPlayer.addAdstartItem(data.adList);
//                        mVideoPlayer.setAdStartTotalTime();
//                    }
//                    getVideoAd4(AdDataInvoker.EndAd);
//                    //				getVideoDetail();
//                    break;
//                case AdDataInvoker.PauseAd:
//                    if (data.adList != null && data.adList.size() > 0) {
//                        AdDataInvoker.AdDataReciver.AdvItemX advItemX = data.adList.get(0);
//                        advItemX.setCanClose(true);
//                        mVideoPlayer.showAdPausevertiseView(advItemX);
//                    }
//                    break;
//                case AdDataInvoker.EndAd://片尾广告请求完了再播放正片
//                    if (data.adList != null && data.adList.size() > 0) {
//                        mVideoPlayer.addAdEndItem(data.adList);
//                        mVideoPlayer.setAdEndTotalTime();
//                    }
//                    //				getVideoDetail();
//                    closeActivityStateView();
//                    break;
//            }
        }

        @Override
        public void fault(Object data) {
            if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
                return;
            }
            Log.w(TAG, "ad fault");
            switch (type) {
                case AdDataInvoker.BufferAd:
                    getVideoAd4(AdDataInvoker.EndAd);
                    break;
                case AdDataInvoker.EndAd:
                    //				getVideoDetail();
                    closeActivityStateView();
                    break;
            }
        }

    }

    boolean isFullScreen = false;

    public void setVideoPlayerData() {

        mVideoPlayer.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }

            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    case VideoView.STATE_PLAYBACK_COMPLETED:
                        try {
                            if (mVideoPlayer.isFullScreen())
                                mVideoPlayer.onBackPressed();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        });
//        mVideoPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
//            @Override
//            public void onPrepared(int currentMediaIndex) {
//                super.onPrepared(currentMediaIndex);
//                mVideoPlayer.toggleFullScreenEnable(true);
//            }
//
//            @Override
//            public void onpause(int currentMediaIndex) {
//                super.onpause(currentMediaIndex);
//                getVideoAd4(AdDataInvoker.PauseAd);
//            }
//
//            @Override
//            public void oncomplete(int currentMediaIndex) {
//                super.oncomplete(currentMediaIndex);
//                try {
//                    if (mVideoPlayer.isFullScreen())
//                        mVideoPlayer.toggleFullScreen();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void ontoggleFullScreen(int currentMediaIndex, boolean isFulls) {
//                super.ontoggleFullScreen(currentMediaIndex, isFulls);
//                // VideoPlayerCollectionState.setCollectionState(getActivity(), articleItem, mVideoPlayer);
//                isFullScreen = isFulls;
//                EventBus.getDefault().post(new Boolean(isFullScreen));
//                if (isFullScreen) {
//                    layoutRootTitleInfo.setVisibility(View.GONE);
//                    mWebView.setVisibility(View.GONE);
//              /*      ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mNewsdetailContent.getLayoutParams();
//                    layoutParams.setMarginStart(0);
//                    layoutParams.setMarginEnd(0);
//                    mNewsdetailContent.setLayoutParams(layoutParams);*/
//                } else {
//                    int marginValue = getResources().getDimensionPixelSize(R.dimen.appfactory_liststyle_marginlr);
//
//                    layoutRootTitleInfo.setVisibility(View.VISIBLE);
//                    mWebView.setVisibility(View.VISIBLE);
//                  /*  ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mNewsdetailContent.getLayoutParams();
//                    layoutParams.setMarginStart(marginValue);
//                    layoutParams.setMarginEnd(marginValue);
//                    mNewsdetailContent.setLayoutParams(layoutParams);*/
//
//
//                    mVideoPlayer.post(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            setVideoLayout();
//                        }
//                    });
//                }
//            }
//        });
    }

    protected void setVideoLayout() {
        int marginValue = getResources().getDimensionPixelSize(R.dimen.appfactory_liststyle_marginlr);
        ViewGroup.LayoutParams videoPlayerLayoutparam = mVideoPlayer.getLayoutParams();
        float num = (float) (16.0 / 9.0);
        int height = (int) ((getResources().getDisplayMetrics().widthPixels - 2 * marginValue) / num);
        videoPlayerLayoutparam.height = height;
        mVideoPlayer.setLayoutParams(videoPlayerLayoutparam);
//        ivVideoThumb.getLayoutParams().height = height;
//        ivVideoThumb.requestLayout();
    }

    protected void initVideoInfo() {
        videoAdDataCallBack = new VideoAdDataCallBack();
        adDataInvoker = new AdDataInvoker(videoAdDataCallBack);

        videoLayout = ((ViewStub) videoLayout).inflate();
        mVideoPlayer = Utility.findViewById(videoLayout, R.id.mBaiduPlayer);
//        mVideoPlayer.setNonWifiTipsMainColor(serverInfo.getMainColor());
//        mVideoPlayer.hideLoadingView();
//        mVideoPlayer.toggleFullScreenEnable(false);
        mVideoPlayer.setClickable(false);
        mVideoPlayer.hideTitleLayoutWhenInNormalState();
//        mVideoPlayer.hideButtonBack();
//        mVideoPlayer.setSmallView(View.VISIBLE);
//        mVideoPlayer.fullScreenAdd2WindowContentLayer = true;
        // ivVideoThumb = Utility.findViewById(videoLayout, R.id.videoThumb);
        setVideoLayout();
        mVideoPlayer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });

        setVideoPlayerData();

        // ImageLoader.getInstance().displayImage(article.getVideo_logo(), ivVideoThumb);
        mVideoPlayer.setPoster(ImageKitKt.buildUrl(3, article.getVideo_logo()), ContextCompat.getDrawable(requireContext(), R.drawable.cctv7_loading_img));
        try {
            JSONObject video = new JSONObject(article.getVideo());
            JSONArray tsAddress = VideoAddressGet.getAddress(video);
            String cdnEncypt = video.optString("cdnConfigEncrypt");
            XVideoItem videoPlayObj = new XVideoItem(article.getTitle());
//            videoPlayObj.setTitle(article.getTitle());
//            videoPlayObj.setVID(article.getVid());

            videoPlayObj.setCdnIv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
            videoPlayObj.setCdnKey(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);

            for (int i = 0; tsAddress != null && i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                //				mVideoPlayer.addMediaItemInfo(new MediaItemInfo(line.optString("title"), line.optString("url")));
                XVideoBitRate lineItem = new XVideoBitRate();
                lineItem.setPath(line.optString("url"));
                lineItem.setTitle(line.optString("title"));
                lineItem.setCdnEncypt(cdnEncypt);
                videoPlayObj.getBitRates().add(lineItem);
            }
            mVideoPlayer.addVideoItem(videoPlayObj, true);
            if (videoPlayObj != null && videoPlayObj.getBitRates() != null &&
                    videoPlayObj.getBitRates().size() > 0) {
                if (mVideoPlayer != null) {
                    mVideoPlayer.setVisibility(View.VISIBLE);
                }
            } else {
                if (mVideoPlayer != null) {
                    mVideoPlayer.setVisibility(View.GONE);
                }
            }
//            mVideoPlayer.getMediaObjs().clear();
//            mVideoPlayer.addMediaObjs(videoPlayObj);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());
            if (mVideoPlayer != null) {
                mVideoPlayer.setVisibility(View.GONE);
            }
        }

//        mVideoPlayer.setAdCliclkListenter(new AdCliclkListenter() {
//
//            @Override
//            public void OnAdCliclkListenter(String LinkUrl, boolean isvideo, AdItem adItem) {
//                Log.w(TAG, "adclick:" + LinkUrl);
//                ArticleItem articleItem = new ArticleItem();
//                articleItem.setUrl(LinkUrl);
//                articleItem.setLinkNews(false);
//                articleItem.setTitle(getString(R.string.adtitile));
//                NewsItemClickUtils.OpenItemNewsHandle(getActivity(), TypeX.NEWS.LINK, articleItem, null, NeedTokenType.Unnecessary, false, false);
//            }
//        });
    }


    protected void getDetail() {
        Map<String, String> params = new HashMap<>();
        params.put("no_content", "1");
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        if (!TextUtils.isEmpty(navigate_id)) {
            params.put("navigate_id", navigate_id);
        }
        DataInvokeUtil.ziMeiTiApi.getArticleById("" + article.getId(), params)
                .map(new Function<Response<JSONObject>, ArticleItemReciver>() {

                    @Override
                    public ArticleItemReciver apply(Response<JSONObject> response) throws Exception {
                        ArticleItemReciver articleItemReciver = new ArticleItemReciver();
                        try {
                            articleItemReciver.readFromJson(response.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return articleItemReciver;
                    }
                })
                .subscribeOn(Schedulers.io())
                .onErrorReturn(new Function<Throwable, ArticleItemReciver>() {
                    @Override
                    public ArticleItemReciver apply(Throwable throwable) throws Exception {
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ArticleItemReciver>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ArticleItemReciver articleItemReciver) {
                        if (getActivity() instanceof MagazineDetailActivity) {
                            ((MagazineDetailActivity) getActivity()).success(articleItemReciver);
                        }
                        success(articleItemReciver);

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

        Map<String, String> params2 = new HashMap<>();
        params2.put("article_id", "" + article.getId());
        params2.put("reads", "1");
        DataInvokeUtil.ziMeiTiApi.readStatisticsCMS(params2)
                .map(new Function<Response<JSONObject>, ReadDataReciver>() {
                    @Override
                    public ReadDataReciver apply(Response<JSONObject> jsonObjectResponse) throws Exception {
                        ReadDataReciver readDataReciver = new ReadDataReciver();
                        try {
                            readDataReciver.readFromJson(jsonObjectResponse.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return readDataReciver;
                    }
                })
                .subscribeOn(Schedulers.io())
                .onErrorReturn(new Function<Throwable, ReadDataReciver>() {
                    @Override
                    public ReadDataReciver apply(Throwable throwable) throws Exception {
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReadDataReciver>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ReadDataReciver readDataReciver) {
                        //reciveReadsCount(readDataReciver);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    public void refreshSupport() {

    }


    @Override
    public void success(ArticleItemReciver data) {
        if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
            return;
        }
        this.mArticleItemReciver = data;
        if (data.state && data.articleItem != null/*&&(article!=null&&article.getId()==data.articleItem.getId())*/) {
            article = data.articleItem;
            webViewInsertHandle.haveVideoArray(article);
            webViewInsertHandle.haveAudioArray(article);
            article.setmShowSwitch(showSwitch);
            MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
            if (activity != null) {
                article.isEPaper = activity.isEpaper;
                activity.articleItem = article;
                activity.refreshBottomStyle(article, 1);
            }
            if (isLoaded)
                MagazineDetailKitKt.setOriginAndReprint(this);
            UserRecommend.addItemKeyWord(article, getActivity());
            if (onDetailNext) { //如果页面已经完成了加载就之际去加载像组件
                if (!activity.isEpaper && !isCalendar) {
                    MagazineDetailKitKt.addComponent(this);
                }
            }
            MagazineDetailKitKt.setNewsTitle(this);
        } else {
            fault(data);
        }
    }

    protected void setContentData() {
        Map<String, String> params = new HashMap<>();
        params.put("article_id", String.valueOf(article.getId()));
        if(!TextUtils.isEmpty(article.getPreview())){
            params.put("preview", article.getPreview());
        }
        DataInvokeUtil.ziMeiTiApi.getArticleContent(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (jsonObject.optBoolean("state")) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            String content = data.optString("content");
                            showHTMLData(content);
                            if (!isCalendar) {
                                setQuickData();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    protected void setNewsInfo() {
        MagazineDetailKitKt.initWeatherView(this);
        article.setIsSupport(serverInfo.cancelSupport);
        if (TextUtils.isEmpty(article.getReferName())) {
            article.setReferName(getResources().getString(R.string.app_name));
        }

    }

    /**
     * 是否需要点赞
     */
    private boolean needSupport() {
        return article.getTagsflag() == 1 && serverInfo.getOtherFunction() != null && serverInfo.getOtherFunction().getSupport() > 0;
    }


    /**
     * 是不是样式
     *
     * @return
     */
    private boolean isQingHaiStyle() {
        CustomColumns custom = article.getCustomColumns();
        return custom != null && "1".equals(custom.getIsQinghaiStyle()) && article.getSpider() == null;
    }

    /**
     * 设置媒体相关的
     */
    protected void setMediaContent() {

//        if (!webViewInsertHandle.haveAudioArray(article) && !TextUtils.isEmpty(article.getAudio())) {
//            Bundle bundle = new Bundle();
//            ArticleItem myArticle = new ArticleItem();
//            myArticle.setId(article.getId());
//            myArticle.setAudio(article.getAudio());
//            myArticle.setAudio_title(article.getAudio_title());
//            myArticle.setAudio_logo(article.getAudio_logo());
//            bundle.putParcelable("data", myArticle);
//            NewsDetailAudioPlayerFragment audioPlayerFragment = new NewsDetailAudioPlayerFragment();
//            audioPlayerFragment.setArguments(bundle);
//            manager = getChildFragmentManager();
//            transaction = manager.beginTransaction();
//            transaction.replace(R.id.audioLayout, audioPlayerFragment);
//            transaction.commitAllowingStateLoss();
//        }
        Log.e("ACVCC", "setMediaContent " + isFromeVod + "   " + webViewInsertHandle.haveVideoArray(article) + "   " + TextUtils.isEmpty(article.getVideo()));
        if (!isFromeVod && !webViewInsertHandle.haveVideoArray(article) && !TextUtils.isEmpty(article.getVideo())) {
            initVideoInfo();
            getVideoAd4(AdDataInvoker.BufferAd);
        }
    }

    /**
     * 积分统计
     */
    private void addintegral() {
        startAddIntegralCounter();
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (article == null) {
                    return;
                }
                Addintegral.addintegral(getActivity().getApplicationContext(), article.getId(), 2, "1".equals(article.getMovie().getIsStudyContent()) ? "1" : "0", article);
            }
        });
    }

    @ShareComponent.AdapterViewItemClicked
    public void onItemClick(AdapterView<?> parent, View view, int position, long id, ShareGridItem item) {
        Log.i(TAG, "@ShareComponent.AdapterViewItemClicked onItemClick" + parent + "view " + view + "position " + position + "id " + id);
        ShareGridClickUtil.ShareGridClickHandle(item.label, article, catalogItem, getActivity());
    }

    @Override
    public void fault(Object data) {
        if (getActivity() == null || requireActivity().isFinishing() || requireActivity().isDestroyed()) {
            return;
        }
        Log.w(TAG, "fault" + data);
        closeActivityStateView();
        if (data != null) {
            if ("3002".equals(((ArticleItemReciver) data).code)) {
                FunKt.toast(getContext(), "您访问的内容不存在");
                mWebView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        final FragmentActivity activity = getActivity();
                        if (activity != null) {
                            activity.finish();
                        }
                    }
                }, 1000);
            } else {
                FunKt.toast(getContext(), ((ArticleItemReciver) data).message);
            }

        }

    }


    public void showHTMLData(String data) {
        orginHTMLData = data;
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.requestFocus();
        job = MagazineDetailKitKt.parseHtml(this, data);

    }


    @JavascriptInterface
    public void openImgAlbum(final int left, final int top, final int offsetWidth, final int offsetHeight, final String imgIndex) throws JSONException {
        if (webImages.size() > 0 && getActivity() != null) {
            JSONArray images = new JSONArray();
            int index = 0;
            for (JSImgItem imgItem : webImages) {
                images.put(index, imgItem.toJsonObject());
                index++;
            }
            final ArticleItem imgArticle = new ArticleItem();
            imgArticle.setTitle(article.getTitle());
            imgArticle.setImage(images.toString());
            imgArticle.setType(TypeX.NEWS.PHOTOS);
            imgArticle.setSpider(article.getSpider());
            imgArticle.setHitCount_format(article.getHitCount_format());
            imgArticle.setPublishdate_format(article.getPublishdate_format());
            imgArticle.setAuthor(article.getAuthor());
            imgArticle.setLocalShareType(-1);
            imgArticle.setLocalSpinder(false);

            JSONObject jsonObject = images.getJSONObject(Integer.parseInt(imgIndex));
            boolean hasATag = jsonObject.optBoolean("hasATag");
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (getActivity() != null) {
                        if (!hasATag)//存在a标签不跳转
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), TypeX.NEWS.PHOTOS, imgArticle, catalogItem, imgIndex);

                    }
                }
            });

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mWebView.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (Intent.ACTION_POWER_CONNECTED.equals(powerStateReciver.getState())) {
            if (mVideoPlayer != null)
                //   mVideoPlayer.isHandModePause = true;
                if (webViewInsertHandle != null)
                    webViewInsertHandle.setIsHandModePause(true);
        } else {
//            if (mVideoPlayer != null) {
//                mVideoPlayer.isHandModePause = false;
//                mVideoPlayer.pagePause = true;
//                mVideoPlayer.pause();
//            }
            if (webViewInsertHandle != null) {
                webViewInsertHandle.setIsHandModePause(false);
                webViewInsertHandle.onPause();
            }
        }
        powerStateReciver.setState(null);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (MMKV.defaultMMKV().getBoolean(XKey.REFRESH_LOCATION, false)) {
            MMKV.defaultMMKV().putBoolean(XKey.REFRESH_LOCATION, false);
            PermissionUtil.INSTANCE.getLocation(requireContext(), new ILocation() {
                @Override
                public void onLocation(@NonNull BDLocation location) {
                    if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
                        return;
                    }
                    if (weatherSetter != null) {
                        weatherSetter.getWeather();
                    }
                }

                @Override
                public void onFail() {

                }
            });
        }
        collectionController.checkCollection();
        boolean isVoteReadyData = isVoteMode && !TextUtils.isEmpty(orginHTMLData) && UserInfo.isLogin(getActivity());
        if (!isVoteReadyData && webViewInsertHandle != null && !webViewInsertHandle.isHandModePause()) {
            webViewInsertHandle.onResume();
        }
//        if (mVideoPlayer != null && !mVideoPlayer.isHandModePause) {
//            mVideoPlayer.resume();
//            mVideoPlayer.adResume();
//        }

        if (isVoteReadyData) {
            if (webViewInsertHandle != null) {
                webViewInsertHandle.destory();
                webViewInsertHandle = null;
                webViewInsertHandle = new WebViewInsertHandle(getActivity(), article, catalogItem, mWebView);
            }
            mWebView.loadUrl("about:blank");
            showHTMLData(orginHTMLData);
        }

    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void rereshSupportButtonStatus(GetSupportEvent event) {
//        if (event.timeStamp != timeStamp || event.getType() == GetSupportEvent.Invoke)
//            return;
//    }

    public void clearWebView() {
        if (mWebView != null) {
            try {
                mWebView.removeJavascriptInterface(Js2GroupImage);
                mWebView.removeJavascriptInterface(ANDROID_IFRAME);
                //  mWebView.destroy();
            } catch (Exception e) {
            }
        }

    }

    private void addDisposable(Disposable d) {
        if (cancelUtils == null) {
            cancelUtils = new CancelUtils();
        }
        cancelUtils.addDisposable(d);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (container != null) {
            container.removeCallbacks(exposureTask);
        }

        isDispose = true;
        if (!threadList.isEmpty()) {
            for (Thread thread : threadList) {
                if (thread.isAlive()) {
                    thread.interrupt();
                }
            }
            threadList.clear();
            threadList = null;
        }


        if (spiderView != null) {
            spiderView.destroy();
        }

        if (cancelUtils != null) {
            cancelUtils.cancelDisposable();
            cancelUtils = null;
        }

        try {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
                handler = null;
            }
            if (HistoryInvoker != null && HistoryInvoker.disposable != null
                    && !HistoryInvoker.disposable.isDisposed()) {
                HistoryInvoker.disposable.dispose();
            }

            orginHTMLData = null;
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }

            if (webViewInsertHandle != null) {
                webViewInsertHandle.destory();
                webViewInsertHandle = null;
            }
            if (job != null) {
                if (job.isActive()) {
                    job.cancel(null);
                }
                job = null;
            }
//        VideoAudioActivityRunningTask.VideoActivity.clear();
//        if (mVideoPlayer != null) {
//            try {
//                mVideoPlayer.stop();
//                mVideoPlayer.onUnregisterReceiver();
//            } catch (Exception e) {
//            }
//        }
            if (adDataInvoker != null)
                adDataInvoker.destory();
            webImages.clear();
            if (article != null)
                article.setContent(null);
        } catch (Exception e) {

        }
//        if (rrf != null) {
//            try {
//                manager = getChildFragmentManager();
//                transaction = manager.beginTransaction();
//                transaction.remove(rrf);
//                transaction.commitAllowingStateLoss();
//            } catch (Exception e) {
//
//            }
//        }

        try {
            getActivity().unregisterReceiver(powerStateReciver);
        } catch (Exception ex) {
        }
        if (mVideoPlayer != null) {
            mVideoPlayer.release();
        }
        if (webViewInsertHandle != null) {
            webViewInsertHandle.destory();
            webViewInsertHandle = null;
        }
    }


    protected void intoLogin(final Activity context) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
                    return;
                }
                LoginUtils.request_source="杂志详情";
//                ToastUtil.show(context, R.string.please_login);
                LoginUtils.invokeLogin(context);
//                Intent intent = new Intent();
//                intent.setClassName(context, ModuleReferenceConfig.LoginActivity);
//                context.startActivity(intent);
            }
        });

    }


    /**
     * 接收阅读数
     *
     * @param reciver
     */

    public void reciveReadsCount(ReadDataReciver reciver) {
        if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
            return;
        }
        if (reciver.state) {
            readResponsed = true;
            AnalysisUtils.readsAnalysis(getActivity(), article, reciver.virtualIncrement);
            MagazineDetailKitKt.setNormalReadNumber(this, reciver.reads);
        } else {
            AnalysisUtils.readsAnalysis(getActivity(), article, reciver.virtualIncrement);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userLoginEvent(LoginEvent loginEvent) {
        if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
            return;
        }
        if (UserInfo.getUserInfo(requireActivity()).isLogin()) {
            if (spiderView != null) {
                spiderView.checkIsAttention();
            }
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void reciveDetailAdData(AdEvent<SSPAdModel> resultAdEvent) {
//        if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()) {
//            return;
//        }
//        if (resultAdEvent.otherData != timeStamp || fromMicroLive)
//            return;
//        try {
//            IAdResultItem media = resultAdEvent.getData().getAdResults().get(0);
//            detailAdTopHolder = new DetailAdvBaseHolder(Utility.findViewById(mRootView, R.id.detailAdTop));
//            ArticleItem adData = new ArticleItem();
//            adData.setType(TypeX.CUSTOM.ADVERT);
//            adData.setTitle(media.getAdTitle());
//            adData.setUrl(media.getClickJumpUrl());
//            adData.setLogo(media.getSrcUrl());
//            adData.setExtendField(resultAdEvent.getData());
//            detailAdTopHolder.setAdData(adData);
//            AfpStaticsUtils.showStatics(media);
//        } catch (Exception e) {
//        }
//    }

    @JavascriptInterface
    public void setIFrameHeight(int height, String act_id) {
        if (iframe_vote_releationship.containsKey(act_id)) {
            if (getActivity() == null)
                return;
//            height= (int) (height*getResources().getDisplayMetrics().density);
            String iframeId = iframe_vote_releationship.get(act_id);
            final String jsCode = "javascript:document.getElementById('" + iframeId + "').height=" + height + ";";
//            final  String jsCode="javascript:document.getElementById('"+iframeId+"').height="+"document.getElementById('"+iframeId+"').body.scrollHeight;";
            Log.w("iframe", jsCode);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mWebView != null)
                        mWebView.loadUrl(jsCode);
                    if (webViewInsertHandle != null)
                        webViewInsertHandle.resizeNativeControl();
                }
            });

        }
    }

    /*public void checkIsAttentioned() {
        if (!UserInfo.isLogin(getActivity()))
            return;
        if (articleItem.getSpider() != null)
            selfMediaAttentionController.getAttentionStatus(articleItem.getSpider().getUserId());

    }*/
    @JavascriptInterface
    public String getXinZhiToken() {
        return AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.xinzhi_token;
    }

    private void showActivityStateView(String type) {
        MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
        if (activity != null) {
            activity.showStateView(type, false);
        }
    }

    protected void closeActivityStateView() {

        MagazineDetailActivity activity = MagazineDetailKitKt.detailActivity(this);
        if (activity != null) {
            activity.closeStateView();
        } else {
            if (getParentFragment() != null && getParentFragment() instanceof MilitaryCalendarFragment) {
                MilitaryCalendarFragment parent = (MilitaryCalendarFragment) getParentFragment();
                parent.closeStateView();
            }
        }
    }

    public void updateBuyContent(PaidMetas paidMetas) {
        try {
            if (article != null) {
                article.orginDataObject.put("audio_arr", new JSONArray(paidMetas.getAudio()));
                article.orginDataObject.put("video_arr", new JSONArray(paidMetas.getVideo()));
                webViewInsertHandle.haveAudioArray(article);
                webViewInsertHandle.haveVideoArray(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void runTask(){
        if (container!=null){
            container.removeCallbacks(exposureTask);
            container.postDelayed(exposureTask,TXReportManager.EXPOSURE_DELAY);
        }
    }
    public Runnable exposureTask = new Runnable() {
        @Override
        public void run() {
            if (container != null ) {
                if (container.getGlobalVisibleRect(new Rect())) {
                    for (int i = 0; i < container.getChildCount(); i++) {
                        View childView = container.getChildAt(i);
                        if (childView.getGlobalVisibleRect(new Rect())) {
                            if (childView instanceof IExposure) {
                                ArrayList<ArticleItem> articleItems = (ArrayList<ArticleItem>) ((IExposure) childView).getExposureArticles();
                                if (articleItems != null && !articleItems.isEmpty()) {
                                            for (ArticleItem item : articleItems) {
                                                TXReportManager.getInstance().app_jhapp_content_detail_rec_imp(item);
                                            }
                                }
                            }
                        }
                    }
                }
            }
        }
    };
}